import unittest
import requests
import pymysql


class TestA3Mall(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.db = pymysql.connect(
            host='10.59.9.14',
            user='root',
            password='yidong666',
            database='a3mall'
        )
        cls.cursor = cls.db.cursor()
        cls.token = None
        cls.goods_id = None
        cls.goods_stock = None

    @classmethod
    def tearDownClass(cls):
        cls.cursor.close()
        cls.db.close()

    def test_01_get_goods_info(self):
        """获取商品信息"""
        self.cursor.execute('SELECT id, store_nums FROM mall_goods WHERE title="测试机003"')
        result = self.cursor.fetchone()
        self.assertIsNotNone(result, "未找到测试商品")

        self.__class__.goods_id = result[0]
        self.__class__.goods_stock = result[1]
        print(f"商品ID: {self.goods_id}, 库存: {self.goods_stock}")

    def test_02_login(self):
        """用户登录"""
        self.assertIsNotNone(self.goods_id, "需要先获取商品信息")

        response = requests.post(
            url='http://10.59.9.14:7003/api/public/login',
            json={"username": "15523615759", "password": "123456Aa"}
        )
        print("登录响应:", response.json())

        self.assertEqual(response.status_code, 200, "登录失败")
        self.__class__.token = response.json()['data']['token']
        self.assertIsNotNone(self.token, "未获取到token")

    def test_03_create_order(self):
        """创建订单"""
        self.assertIsNotNone(self.token, "需要先登录")
        self.assertIsNotNone(self.goods_id, "需要先获取商品信息")

        order_data = {
            "id": str(self.goods_id),
            "type": "buy",
            "address_id": 278,
            "store_id": 1,
            "shipping_type": 1,
            "bonus_id": "0",
            "payment": "balance",
            "remarks": "",
            "source": 1,
            "url": f"http://10.59.9.14:7003/wap/pages/cart/confirm?id={self.goods_id}&sku_id=&num=1&type=buy",
            "sku_id": "",
            "num": "1"
        }

        response = requests.post(
            url='http://10.59.9.14:7003/api/order/create',
            headers={'Auth-token': f'Bearer {self.token}'},
            json=order_data
        )
        print("订单创建响应:", response.json())

        self.assertEqual(response.status_code, 200, "订单创建失败")

        # 验证数据库中的库存是否减少
        self.cursor.execute('SELECT store_nums FROM mall_goods WHERE id=%s', (self.goods_id,))
        new_stock = self.cursor.fetchone()[0]
        print(new_stock)
        self.assertEqual(new_stock, self.goods_stock)